package com.aididi.controller;

import com.aididi.entity.ContractorInfo;
import com.aididi.mapper.ContractorInfoMapper;
import com.aididi.utils.operationTypeEnum;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Controller
@RequestMapping("/upload")
@Slf4j
public class FileUploadController {

    @Autowired
    ContractorInfoMapper contractorInfoMapper;

    @ResponseBody
    @RequestMapping("/getFileToByte")
    public JSONObject upload(@RequestParam(value="files",required=false) MultipartFile multipartFile, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String fileName = multipartFile.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!"txt".equals(suffixName)) {
            json.put("result", false);
            json.put("msg", "文件格式不符合");
            return json;
        }
        List<String> list = null;
        try {
            list = this.readTxt(multipartFile);
        } catch (IOException e) {
            log.info("文件解析失败", e.getMessage());
            json.put("result", false);
            json.put("msg", "文件解析失败");
            return json;
        }

            log.info("list:{}", list);
            if (CollectionUtils.isEmpty(list)) {
                log.info("文件为空");
                json.put("result", false);
                json.put("msg", "文件为空，请重新上传");
                return json;
            }
            String[] str = list.get(0).trim().split(",");
            if(str.length != 2){
                json.put("result", false);
                json.put("msg", "汇总行必须是由【行数、操作类型】组成");
                return json;
            }
            int num = Integer.parseInt(str[0].trim());
            String operationType = str[1].trim();
            int len = list.size();
            String reg = "^[01]+$";
            if (num != list.size() - 1) {
                log.info("汇总行数与明细总行数不一致");
                json.put("result", false);
                json.put("msg", "汇总行与明细总行数不一致，请重新上传");
                return json;
            }
            operationTypeEnum dt = operationTypeEnum.getType(operationType);
            if(dt==null){
                json.put("result", false);
                json.put("msg", "操作类型不正确");
                return json;
            }
            switch (dt) {
                case TYPE_00:
                    for (int i = 1; i < len; i++) {
                        String[] detail = list.get(i).trim().split(",");
                        if(detail.length != 3){
                            json.put("result", false);
                            json.put("msg", "明细行不对");
                            return json;
                        }
                        String matchNo = detail[0].trim();
                        String appType = detail[1].trim();
                        String authStr = detail[2].trim();
                        if (authStr.length() != 3 || !authStr.matches(reg)) {
                            log.info("商户 {},{} 的权限值：{} 不符合规范，必须是3位且由0或1组成", matchNo, appType, authStr);
                            json.put("result", false);
                            json.put("msg", "商户:" + matchNo + "的权限值：" + authStr + "不符合规范，必须是3位并且由0和1组成");
                            return json;
                        }
                        ContractorInfo contractorInfo1 = contractorInfoMapper.findByMchntNoAndAppType(matchNo, appType);
                        if (null == contractorInfo1) {
                            log.info("商户{}，不存在", matchNo);
                            json.put("result", false);
                            json.put("msg", "商户：" + matchNo + "不存在");
                            return json;
                        }
                        contractorInfo1.setStatus(authStr);
                        contractorInfoMapper.save(contractorInfo1);
                        json.put("result", true);
                    }
                    break;
            }

        return json;
    }


    private List<String> readTxt(MultipartFile multipartFile) throws IOException {
        String s = "";
            List<String> list = new ArrayList<>();
            FileInputStream bi = (FileInputStream) multipartFile.getInputStream();
            InputStreamReader isr = new InputStreamReader(bi,"utf-8");
            BufferedReader br = new BufferedReader(isr);
            String lineText;
            while ((lineText = br.readLine()) != null) {
                list.add(lineText);
            }


        return list;
    }



}
